Skip to content

llama: device snapshots keyed by id (transactional, typed) and pages saved off the main thread; checkpoints as parked sequence ids (host-pool slice 4) - #137

Open
joelteply wants to merge 14 commits into
fable/host-pool-s4from
fable/device-snapshots-s4
Open

joelteply wants to merge 14 commits into
fable/host-pool-s4from
fable/device-snapshots-s4

Conversation

@joelteply

Copy link
Copy Markdown

Slice 4 of the unmerged fable/host-pool work, stacked on #136. This is the library side of moving a mind's state by id and by reference instead of serializing it (CONTINUUM-ENGINE 4.7.11).

What it adds

  • llama_state_seq_snapshot_save/load/free: device snapshots keyed by a caller's snapshot id.
    • They are transactional, validated and typed; device IO commits explicitly, never from a destructor.
    • A failed replacement keeps the prior snapshot.
    • A failed restore quarantines its target and proves the target is cleared; an uncleared target is reported as TARGET_UNCLEARED and stays in the caller's custody.
  • A page saved off the main thread: a device snapshot is taken on the main thread, and a writer thread writes the file from it while decoding continues.
  • test-seq-park: proves a checkpoint can be a parked sequence id against a cold run, including the server's partial-state form.

Cherry-picked with -x from fable/host-pool. Codex's reviews of 7ca9509 and be11e44 are folded into the original commits.

Measured (qwen35-0.8b, hybrid, M5, 2026-11-16)

Old path New path
Checkpoint serialized 23.9 MB in 2.8 ms parked: 0 bytes moved; park 87 µs, restore 190 µs
Partial checkpoint (server form) serialized 20.2 MB in 1.2 ms parked: 0 bytes; park 81 µs, restore 165 µs
Device snapshot — 20.2 MB on device (equal to the quote); save 1.3 ms, restore 370 µs
Page save 7.7 ms synchronous on the main thread 1.6 ms on the main thread, then a writer thread while decoding continues; the file is byte-identical and restores
  • Restored logits match the cold run in every case: max |diff| 0.0044, argmax 82 vs 82.
  • 200 save/free cycles of 4 snapshots: footprint 3,423.4 MiB at base, 3,481.3 MiB at peak, 3,423.4 MiB after.
  • Fault replays: ok.
  • 0 warnings.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

joelteply and others added 8 commits November 16, 2026 13:18
…n (0 bytes moved vs a 23.9 MB serialize)

Joel 2026-11-16: "Pass raw memory by reference ... never encode decode ever ... Pass textures by id
don't rasterize." A server checkpoint today serializes the sequence out of device memory
(llama_state_seq_get_data) and parses it back on restore. The fork's memory already offers the
by-id form: llama_memory_seq_cp shares attention KV cells by sequence id, and recurrent state is
copy-on-write on the device (find_slot moves a sharing sequence to an empty cell with src = the
shared one; the step graph gathers it via s_copy), so a checkpoint is a parked sequence id.

test-seq-park (-m <model>): prefill 300 tokens on seq 0, park it (seq_cp 0 -> 1), advance seq 0
through 120 other tokens, restore (seq_rm 0; seq_cp 1 -> 0), decode the next token, and compare its
logits with a cold run over the same prefix. Receipt, qwen35-0.8b (hybrid=1), this build, M5 Metal:
serialized checkpoint 23,894,492 bytes in 1,783 us; parked checkpoint 0 bytes moved, park 13 us,
restore 40 us; restored vs cold logits max |diff| 0.0044, argmax 82 = 82 (the difference is batch
shape: the cold run decodes 301 tokens in one batch, the restored one 300 + 1). Builds with 0
warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 6c97139)
…recurrent cell, proven

The server's checkpoints hold only the PARTIAL state (LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY: recurrent /
SWA) and trim attention by position. The parked form of exactly that: seq_cp(live, parked, 0, 0) (an
empty attention range copies no KV cells; the recurrent half takes the live cell by id), the live
sequence advances, then restore in the server's order: seq_cp(parked, live, 0, 0) for the recurrent
cell, then seq_rm(live, N, -1) to trim attention.

Receipt, qwen35-0.8b (hybrid), this build, M5 Metal, 300-token prefix: today's partial serialize
20,201,932 bytes in 1,190 us; parked 0 bytes, holding no attention cells (seq_pos_max of the parked
id = -1), park 3 us, restore 29 us; restored next-token logits equal a cold run's (argmax 82 = 82,
max |diff| 0.0044, batch shape). The full-sequence case still passes (23.9 MB vs 0 bytes, 13/27 us).
On unified memory the parked cell occupies the same bytes as the copy, in device memory: the win is no
copy, no duplicate host buffer, no compressor; the count is budgeted (n_seq_max at load).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit be79edc)
…th with context (target partial state is constant: 20,201,932 bytes at 300, 1,500 and 3,000 tokens on qwen35-0.8b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 928194f)
…q_snapshot_save/load/free), prototype for review

CONTINUUM-ENGINE 4.7.11 revised design (proposed for Codex's review; not wired into the server).
Parked sequence ids cost ~81 MB each on the 0.8B with MTP (every recurrent cell carries 1 + n_rs_seq
rollback rows). The fork's LLAMA_STATE_SEQ_FLAGS_ON_DEVICE already copies a sequence's state tensors
into device buffers with backend ops, but keys them by sequence id (mem_storage[seq_id]), so each
snapshot replaced the last. llama_state_seq_snapshot_save/load/free key a snapshot by a caller id:
the snapshot owns a small host header and its own device buffers; load copies them back; free
releases them. A checkpoint becomes a device copy into memory named by handle, with no extra
sequence ids and no rollback rows.

Receipt, qwen35-0.8b (hybrid), this build, M5 Metal, a context with n_seq_max = 1, PARTIAL_ONLY:
20,201,472 device bytes per snapshot at both 300 and 3,000 tokens (one recurrent row, the same as
the serialized partial state; no rollback planes); save 1.3-1.4 ms, restore 0.4-0.8 ms; the restored
next-token logits equal a cold run's (argmax 82 = 82, max |diff| 0.0044-0.0045, batch shape). Save
allocates a fresh device buffer per snapshot: recycling pool-owned buffers is the next measurement.
Device buffers are wired (never compressed or swapped): the pool budgets them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 7ca9509)
…e IO commits explicitly (Codex's review of 7ca9509)

1. Transactional save: the state is staged into separate snapshot storage, copied, and only then
   published under the id; a failed save (typed ALLOC_FAILED) leaves the previous snapshot loadable.
   During a replacement both generations exist; llama_state_seq_snapshot_bytes quotes the device
   bytes BEFORE anything allocates so the pool reserves exactly that (quote == held, asserted).
2. Provenance and validation before mutation: a snapshot stores its flags and its tensor layout
   (which tensors, how many bytes each; offsets excluded, a recurrent sequence may change cells). A
   load first runs a metadata-only write pass over the target and refuses (INCOMPATIBLE) on a flags or
   layout mismatch BEFORE state_seq_read_data touches cell metadata. The reader no longer aborts on a
   mismatch (it checks every buffer type, counts, totals and per-tensor sizes before any copy).
   Typed llama_snapshot_status (OK, ABSENT, INCOMPATIBLE, ALLOC_FAILED, COPY_FAILED); no exception
   crosses the C API.
3. Device IO commits explicitly: llama_io_write_device / llama_io_read_device gain commit() (typed,
   never throws or aborts) and discard(); every snapshot path discards on an exception, so nothing is
   allocated, copied, or half-read in a destructor. Upstream's own ON_DEVICE path is unchanged (its
   destructors still commit and abort on failure). Save, load and free synchronize first, so no
   submitted step reads or writes buffers being replaced or freed.

Native fault replays (test-seq-park, qwen35-0.8b hybrid, n_seq_max 1, PARTIAL_ONLY, M5, at 300 and
3,000 tokens): a failed replacement (injected allocation failure) keeps the prior snapshot, which
then restores the cold-run logits; an incompatible-flags load and an unknown id are refused with the
live state byte-identical (serialized witness); save and free with decode work still in flight; 200
save/free cycles of 4 snapshots return the process footprint to base exactly (433.0 -> peak 490.9 ->
433.0 MiB; 474.2 -> 532.1 -> 474.2), the peak being the staged-replacement overlap. Per snapshot:
20,201,472 device bytes (one recurrent row), save 1.4-1.5 ms, restore 0.4-0.8 ms, restored logits
equal a cold run (argmax equal, max |diff| 0.0044). 0 build warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit be11e44)
…lure quarantines the target; physical byte quotes (Codex's re-review of be11e44)

1. The device writer and reader take auto_commit; every snapshot path constructs them with false, so
   nothing is allocated or copied by a destructor whatever unwinds (be11's save called io.layout(),
   which allocates, outside the try while the writer would still commit on unwinding). Upstream's own
   ON_DEVICE path keeps auto_commit and its abort, unchanged.
2. state_seq_read_data mutates cell metadata before the copy commits: any failure after the read
   begins QUARANTINES the target (seq_rm over its whole range) and returns COPY_FAILED, so a caller sees
   a cold sequence, never a half-restored one; the snapshot itself stays intact and restores it. An
   empty target (fresh or quarantined) restores from the header; a non-empty one is still validated by
   a metadata-only dry pass before anything is touched.
3. Quotes and holdings are PHYSICAL: llama_state_seq_snapshot_bytes = host header + every tensor
   padded to its buffer type's alignment + ggml metadata contexts; save reports the buffers' actual
   sizes + metadata + header; the test requires quote == held.

Native fault replays (qwen35-0.8b hybrid, n_seq_max 1, PARTIAL_ONLY, M5, at 300 and 3,000 tokens):
quote == held == 20,228,428 bytes; failed replacement keeps the prior; incompatible/absent refused
with the live state byte-identical; injected post-read commit failure -> COPY_FAILED, target emptied
(seq_pos_max -1), intact snapshot restores it; save/free with work in flight; 200 save/free cycles of
4 return the footprint to base exactly (433.1 -> 491.0 -> 433.1 MiB; 472.6 -> 530.5 -> 472.6). Save
1.3-1.4 ms, restore 0.35-0.40 ms; restored logits equal a cold run. 0 build warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 16a02cc)
…le written by a writer from the snapshot)

CONTINUUM-ENGINE 4.7.13, audit row 6, measured: a page save ran on the engine's main loop
(llama_state_seq_save_file) and stalled every co-resident stream (a 201 MB page: 114-135 ms per save;
slot 1's median inter-token gap 7 ms -> 103-131 ms, p99 to 2 s).

llama_state_seq_snapshot_write_file writes a FULL-sequence device snapshot (saved with flags 0) as the
standard state file from the snapshot alone (magic | version | n_tokens | tokens | the state stream
with each tensor's bytes spliced into the snapshot header at the positions the writer recorded;
host-visible buffers written straight from the buffer). It never touches the context's live state,
so it runs on a writer thread while the context decodes. Snapshots are shared_ptrs under a mutex, so
a writer keeps its snapshot alive if the main thread frees or replaces the id meanwhile.

test-seq-park (qwen35-0.8b, M5), the main thread's cost per save, synchronous vs snapshot (+ the
write on a writer thread while the context keeps decoding): 24 MB page 17.5 ms vs 1.8 ms (+14.8);
57 MB 11.9-41.7 ms vs 3.9-4.1 ms (+10.4-39.0); 193 MB (14,000 tokens) 71.2 ms vs 13.1 ms (+131).
Every snapshot-written page is BYTE-IDENTICAL to llama_state_seq_save_file's and, loaded back,
restores the cold-run logits (max |diff| 0.0044-0.0048). The test's decode helper now feeds prompts
in n_batch chunks and takes the context size from -c. 0 build warnings. Server wiring (SLOT_SAVE ->
snapshot + writer module, temp path + rename) is next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 4121063)
…ed target is TARGET_UNCLEARED, kept in the caller's custody

Codex's review of 16a02cc: the post-read failure path called llama_memory_seq_rm and ignored its result,
then returned COPY_FAILED, which promises an empty (cold) target. If the clear failed, a half-restored
sequence was reported cold and could be served or reused. Now quarantine() succeeds only when seq_rm
reports success AND the sequence holds no position afterwards; otherwise the load returns the new
LLAMA_SNAPSHOT_TARGET_UNCLEARED, and the header states the caller keeps custody of the sequence (never
serves, parks or returns it) until its own clear succeeds. The header also states the owner-attribution
rule: on COPY_FAILED the sequence holds no one's state, so the caller drops any record that it holds a
mind's tokens.

Test (test-seq-park 2c, qwen35-0.8b): a forced load-commit failure plus a forced clear failure returns
TARGET_UNCLEARED; the custodian's clear then succeeds; every existing case still passes. 0 build warnings.
Fault hook llama_state_seq_snapshot_test_fail_next_quarantine_clears uses the same CAS countdown as the
existing load-commit hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 252f36d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant